package com.xuyiwei.mayi.controller;

import com.xuyiwei.mayi.base.BaseApiService;
import com.xuyiwei.mayi.base.ResponseBase;
import com.xuyiwei.mayi.constants.Constants;
import com.xuyiwei.mayi.entity.UserEntity;
import com.xuyiwei.mayi.feign.MemberServiceFegin;
import com.xuyiwei.mayi.utils.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;

/**
 * Created by xuyiwei on 2019/4/28.
 */
@Controller
public class LoginController  extends BaseApiService{
    private String INDEX = "redirect:/";
    private String LOGIN = "login";

    @Autowired
    private MemberServiceFegin memberServiceFegin;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(){
        return LOGIN;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(UserEntity userEntity, HttpServletRequest request, HttpServletResponse response){
        if(userEntity==null){
            request.setAttribute("error","账号密码不能为空");
            return LOGIN;
        }
        if(StringUtils.isBlank(userEntity.getUsername())){
            request.setAttribute("error","账号不能为空");
            return LOGIN;
        }
        if(StringUtils.isBlank(userEntity.getPassword())){
            request.setAttribute("error","密码不能为空");
            return LOGIN;
        }

        ResponseBase responseBase = memberServiceFegin.login(userEntity);
        if(!Constants.HTTP_RES_CODE_200.equals(responseBase.getCode())){
            request.setAttribute("error","登录失败,账号密码错误");
            return LOGIN;
        }
        LinkedHashMap map = (LinkedHashMap) responseBase.getData();
        String token = (String) map.get("memberToken");
        ResponseBase user = memberServiceFegin.findUserByToken(token);
        if(user!=null){
            CookieUtil.addCookie(response, Constants.COOKIE_MEMBER_TOKEN, token, Constants.COOKIE_TOKEN_MEMBER_TIME);
            return INDEX;
        }else {
            request.setAttribute("error","密码不能为空");
            return LOGIN;
        }
    }
}
